package com.sgcc.nfc.lock.presentation.rooms

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.snackbar.Snackbar
import com.sgcc.nfc.lock.databinding.FragmentRoomsBinding
import com.sgcc.nfc.lock.domain.model.Room
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class RoomsFragment : Fragment() {

    private var _binding: FragmentRoomsBinding? = null
    private val binding get() = _binding!!
    private val viewModel: RoomsViewModel by viewModels()
    private val roomAdapter = RoomAdapter(::onRoomClicked)

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentRoomsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupRecycler()
        setupListeners()
        observeNavigationResults()
        observeViewModel()
    }

    private fun setupRecycler() {
        binding.roomRecycler.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = roomAdapter
        }
    }

    private fun setupListeners() {
        // 实时搜索监听器
        binding.roomSearchInput.addTextChangedListener(object : android.text.TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: android.text.Editable?) {
                viewModel.search(s?.toString().orEmpty())
            }
        })
        
        // 搜索键监听器（保留原有功能）
        binding.roomSearchInput.setOnEditorActionListener { v, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                viewModel.search(v.text?.toString().orEmpty())
                // 隐藏键盘
                val imm = requireContext().getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as android.view.inputmethod.InputMethodManager
                imm.hideSoftInputFromWindow(v.windowToken, 0)
                true
            } else {
                false
            }
        }
        
        binding.addRoomFab.setOnClickListener {
            findNavController().navigate(com.sgcc.nfc.lock.R.id.roomFormFragment)
        }
    }

    private fun observeNavigationResults() {
        findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<Boolean>(RoomFormFragment.RESULT_KEY_ROOM_UPDATED)?.observe(
            viewLifecycleOwner
        ) { updated ->
            if (updated == true) {
                viewModel.loadRooms(viewModel.currentKeyword())
                findNavController().currentBackStackEntry?.savedStateHandle?.remove<Boolean>(RoomFormFragment.RESULT_KEY_ROOM_UPDATED)
            }
        }
    }

    private fun observeViewModel() {
        viewModel.rooms.observe(viewLifecycleOwner) { rooms ->
            roomAdapter.submitList(rooms)
            binding.roomEmptyView.isVisible = rooms.isEmpty()
        }
        viewModel.isLoading.observe(viewLifecycleOwner) { isLoading ->
            binding.roomLoading.isVisible = isLoading
            if (isLoading) {
                binding.roomEmptyView.isVisible = false
            }
        }
        viewModel.error.observe(viewLifecycleOwner) { error ->
            error?.let { Snackbar.make(binding.root, it, Snackbar.LENGTH_LONG).show() }
        }
    }

    private fun onRoomClicked(room: Room) {
        val bundle = Bundle().apply { putLong("roomId", room.roomId) }
        findNavController().navigate(com.sgcc.nfc.lock.R.id.roomDetailFragment, bundle)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
